/**
 * 
 *  NFC 模块使用
 * 
 * 
 * 
 * Code By: HelloKun 2021.09.03
 */

#include <stddef.h>
#include <stdio.h>
#include "iot_errno.h" //==IOT_SUCCESS =0 

#include "hi_io.h"
#include "hi_i2c.h"
#include "nfc_bingo.h"

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

/**
 * @ I2C write one byte data;
 * 
 */ 
static uint32_t I2cWiteByte(uint8_t regAddr, uint8_t byte)
{
    hi_i2c_idx id = NFC_I2C_IDX;
    uint8_t buffer[] = {regAddr, byte};
    hi_i2c_data i2cData;

    i2cData.send_buf = buffer;
    i2cData.send_len = sizeof(buffer)/sizeof(buffer[0]);

    //return IoTI2cWrite(id, OLED_I2C_ADDR, &i2cData,i2cData.send_len); //==iot_i2c.h
    return hi_i2c_write((hi_i2c_idx)id, NFC_I2C_ADDR, &i2cData);  //==hi_i2c.h
}

/**
 * @brief Write a command byte to NFC device.
 * @param cmd the commad byte to the writen.
 * @return Returns{@link IOT_SUCCESS} if the operation is successful;
 *  returns an error code defined in {@link iot_errno.h} otherwise.
 * */ 
static uint32_t WriteCmd(uint8_t cmd)
{
     return I2cWiteByte(NFC_I2C_ADDR,cmd);
}

/**
 * @brief Write a data byte to NFC device.
 * @param 16bit regAddr, 8nit data 
 * @return Returns{@link IOT_SUCCESS} if the operation is successful;
 * return an error code defined in {@link iot_errno.h} otherwise.
 */
static uint32_t WriteData(uint16_t regAddr,uint8_t data)
{
    return I2cWiteByte(regAddr,data);
}

/**
 * @brief Read a data byte from  NFC device.
 * @param  16bit regAddr, 8bit data
 * @return *data
 * */
static uint32_t I2CReadByte(uint16_t regAddr, uint8_t byte)
{
    hi_i2c_idx id = NFC_I2C_IDX;
    uint8_t buffer[] = {regAddr, byte};
    hi_i2c_data i2cData;

    i2cData.send_buf = buffer;
    i2cData.send_len = sizeof(buffer)/sizeof(buffer[0]);
    return hi_i2c_read((hi_i2c_idx)id,regAddr, &i2cData);
}

/**
 * @brief Read a data byte from  NFC device.
 * @param  16bit regAddr, 8bit data
 * @return *data
 * */
uint32_t ReadData(uint16_t regAddr, uint8_t data)
{
    return I2CReadByte(regAddr,data);
}


/**
 * @brief  FM11NC08I NFC Initialize.
 */
uint32_t NFC_Init()
{
    static const uint8_t initCmds[]={
        0xAF, //==NFC slave地址默认 b1010111（0x57） 最低位 默认0-写、1读
       
    };

    hi_io_set_func(NFC_SDA_IO13,HI_IO_FUNC_GPIO_13_I2C0_SDA);
    hi_io_set_func(NFC_SCL_IO14,HI_IO_FUNC_GPIO_14_I2C0_SCL);
    hi_i2c_init(NFC_I2C_IDX,NFC_I2C_BAUDRATE);
    printf("NFC Initialize Begin!\n");

    for (size_t i = 0; i < ARRAY_SIZE(initCmds); i++) {
        uint32_t status = WriteCmd(initCmds[i]);
        if (status != IOT_SUCCESS) {
            return status;
        }
    }
    WriteData(NFC_CONFIG_ADDR,NFC_CFG_MODE3); //设置EEPROM  ISO14443-3
    

    return IOT_SUCCESS;

}
